package edu.unlv.cs.ladders.web;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import edu.unlv.cs.ladders.entities.Challenge;
import edu.unlv.cs.ladders.entities.Event;
import edu.unlv.cs.ladders.services.PermissionService;

import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;

@RequestMapping("/challenge/**")
@Controller
public class ChallengeController {
	@PreAuthorize("hasRole('ROLE_PARTICIPANT')")
    @RequestMapping(value = "/challenge", method = RequestMethod.POST)
    public String create(@Valid Challenge challenge, BindingResult result, ModelMap modelMap) {
        if (challenge == null) throw new IllegalArgumentException("A challenge is required");
        if (result.hasErrors()) {
            modelMap.addAttribute("challenge", challenge);
            modelMap.addAttribute("events", Event.findAllEvents());
            return "challenge/create";
        }
        challenge.persist();
        getPermissionService().setDefaultPermissions(challenge);
        return "redirect:/challenge/" + challenge.getId();
    }


	@PreAuthorize("hasPermission(#challenge, 'write') or hasRole('ROLE_COORDINATOR')")
    @RequestMapping(method = RequestMethod.PUT)
    public String update(@Valid Challenge challenge, BindingResult result, ModelMap modelMap) {
        if (challenge == null) throw new IllegalArgumentException("A challenge is required");
        if (result.hasErrors()) {
            modelMap.addAttribute("challenge", challenge);
            modelMap.addAttribute("events", Event.findAllEvents());
            return "challenge/update";
        }
        challenge.merge();
        return "redirect:/challenge/" + challenge.getId();
    }

	@PreAuthorize("hasRole('ROLE_PARTICIPANT')")
    @RequestMapping(value = "/challenge/form", method = RequestMethod.GET)
    public String createForm(ModelMap modelMap) {
        modelMap.addAttribute("challenge", new Challenge());
        modelMap.addAttribute("events", Event.findAllEvents());
        return "challenge/create";
    }
    
    @RequestMapping(value = "/challenge/{id}", method = RequestMethod.GET)
    public String show(@PathVariable("id") Long id, ModelMap modelMap) {
        if (id == null) throw new IllegalArgumentException("An Identifier is required");
        modelMap.addAttribute("challenge", Challenge.findChallenge(id));
        return "challenge/show";
    }
    
    @RequestMapping(value = "/challenge", method = RequestMethod.GET)
    public String list(@RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, ModelMap modelMap) {
        if (page != null || size != null) {
            int sizeNo = size == null ? 10 : size.intValue();
            modelMap.addAttribute("challenges", Challenge.findChallengeEntries(page == null ? 0 : (page.intValue() - 1) * sizeNo, sizeNo));
            float nrOfPages = (float) Challenge.countChallenges() / sizeNo;
            modelMap.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
        } else {
            modelMap.addAttribute("challenges", Challenge.findAllChallenges());
        }
        return "challenge/list";
    }

	@PreAuthorize("hasPermission(#challenge, 'write') or hasRole('ROLE_COORDINATOR')")
    @RequestMapping(value = "/challenge/{id}/form", method = RequestMethod.GET)
    public String updateForm(@PathVariable("id") Long id, ModelMap modelMap) {
        if (id == null) throw new IllegalArgumentException("An Identifier is required");
        modelMap.addAttribute("challenge", Challenge.findChallenge(id));
        modelMap.addAttribute("events", Event.findAllEvents());
        return "challenge/update";
    }
    
	@PreAuthorize("hasRole('ROLE_ADMIN')")
    @RequestMapping(value = "/challenge/{id}", method = RequestMethod.DELETE)
    public String delete(@PathVariable("id") Long id, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size) {
        if (id == null) throw new IllegalArgumentException("An Identifier is required");
        Challenge.findChallenge(id).remove();
        return "redirect:/challenge?page=" + ((page == null) ? "1" : page.toString()) + "&size=" + ((size == null) ? "10" : size.toString());
    }
	private PermissionService permissionService;
	@Autowired
	public void setPermissionService(PermissionService permissionService) {
		this.permissionService = permissionService;
	}


	public PermissionService getPermissionService() {
		return permissionService;
	}

}
